const utils = require('../../../common/util/util')

const app = getApp()

Component({
    options: {
        addGlobalClass: true
    },
    properties: {
        'xuuid':{
            type: String,
            value: ''
        },
        'xdata': {
            type: Object,
            value: {}
        },
        'xootd': {
            type: Object,
            value: {}
        },
        'xweek': {
            type: String,
            value: ''
        },
        'xturn': {
            type: Boolean,
            value: false
        },
        'xheight': {
            type: Boolean,
            value: false
        },
        'xpid': {
            type: String,
            value: ''
        },
        'xppid': {
          type: String,
          value: ''
      }
    },
    observers: {
        /* 异步取值 */
        'xdata': function (n) {
            let that = this
            that.setData({
                eva: n.subjects
            })
        },

        'xootd': function (n) {
            let that = this
            that.setData({
                oeva: n.subjects
            })
        },

        'xweek': function (n) {
            console.log('week', n)
            let that = this
            that.setData({
                week: n
            })
        },
        'xturn': function (n) {
            let that = this
            // console.log(n)
            that.setData({
                turn: n
            })
        },
        'xheight': function (n) {
            let that = this
            // console.log(n)
            if (n == true) {
                that.setData({
                    maxheight: 100
                })
            }
        },
        'xpid': function (n) {
            let that = this
            // console.log(n)
            that.setData({
                pid: n
            })
        },
        'maxheight': function () {
            
        }
    },
    data: {
        oindex: 0, // 当前题数初始化
        eva: [],
        oeva: [],
        endstate: false,
        width: 0,
        warning: '', // 测试评语
        maxwidth: '100',
        maxheight: '0',
        turn: false,
        pid: '',
        sex: ["女", "男"],
        education: ["小学", "初中", "高中", "中专", "大专", "本科", "硕士", "博士"],
        marriage_love_state: ["单身", "已婚", "离婚", "丧偶", "恋爱中"],
        all_child: ['无子女','1个','2个','3个及以上'],
        form: {
            real_name: '',
            birthday: '',
            sex: '',
            work: '',
            city: '',
            marriage_love_state: '',
            all_child: '',
            education: '',
            other_drugs: '',
            history_major_diseases: '',
            war_name: '',
            war_phone: '',
            war_ship: '',
        },
        height: false,
        showtreeq:false,
        xpractice:[{
          name:'音频练习',
          id:0,
        path:'/subtool/pages/rudio/index/index'
        }, {
          name: '书写练习',
          id: 1,
          path: '/subtool/pages/dayremb/index/index'
        }, {
          name: '心理测评',
          id: 2,
          path: '/subtool/pages/evaluate/index/index'
        }, {
          name: '小组',
          id: 3,
          path: '/subtool/pages/community/tie/index'
        }],
        
    },
    lifetimes: {
        ready: function () {
            let that = this
            let height = that.data.maxheight
            that.xGetUser()
        }
    },
    methods: {
        /* 选择事件 */
        xSelect: function (e) {
            let that = this;
            let width = 0
            let week = that.data.week
            let eva = that.data.eva // 当前题的列表
            let key = that.data.oindex // 当前的题数
            let index = e.currentTarget.dataset.index // 当前点击的选项
            // console.log(that.properties.xppid)
            for (var i in eva[key].options) {
                delete eva[key].options[i].check
            }
            eva[key].options[index].check = true
            width = (key + 1) / eva.length.toFixed() * 100
            /* 最后一个问题处理 */
            
            if (key === eva.length - 1) {
                that.setData({
                    eva: eva,
                    width: width,
                    endstate: true,
                })
                // week == 0 ||
                if ( week == 1 || week == 2) {
                    that.setData({
                        maxwidth: 100,
                        maxheight: 100
                    })
                    // console.log(that.form)
                    // that.xGetUser()
                }
                return false
            }

            key = key + 1 > eva.length - 1 ? eva.length - 1 : key += 1
            that.setData({
                eva: eva,
                width: width
            })
            setTimeout(() => {
                that.setData({
                    animation: 'animation',
                    oindex: key,
                })
            }, 300)
        },

        aniamtion: function () {
            let that = this
            that.setData({
                animation: ''
            })
        },

        xPrev: function () {
            let that = this
            let key = that.data.oindex
            key = key - 1
            setTimeout(() => {
                that.setData({
                    animation: 'animations',
                    oindex: key,
                })
            }, 300)
        },

        xSave: function (e) {
            let that = this
            let form = that.data.form
            delete form._id
            delete form._openid
            delete form.user_id
            app.authorizeLogin(e, async function () {
                wx.showLoading({
                    title: '提交中',
                    mask: true
                })
                let key = [
                    'real_name' , 'birthday' , 'sex' , 'work' , 'city' ,
                    'marriage_love_state' , 'all_child' , 'education' ,
                    'war_name' , 'war_phone' , 'war_ship'
                ]
                for(var i = 0 ; i < key.length ; i++){
                    if(form[key[i]] == '' || form[key[i]] == undefined){
                        wx.showToast({
                            title: '请完善您的资料',
                            icon: 'none'
                        })
                        return false
                    }else{
                        that.xSubmit()
                    }
                }
            });
            
        },
        xSubmit: async function () {
            let that = this
            let form = that.data.form
            let week = parseInt(that.data.week)
            let pid = that.data.pid
            delete form._id
            delete form._openid
            delete form.user_id
            let eva = that.data.eva
            let data = that.properties.xdata
            let warning = data.results_assessment
            let xRes = 0
            let xData = that.properties.xootd
            let xDeva = eva.slice(9)
            eva = eva.splice(0, 9)
            let xWarning = xData.results_assessment
            /* 只存在一个数据的时候则全部不提交 */
            if (xData == '' || xData === undefined) {
                return false
            }
            for (var i in eva) {
                let opt = eva[i].options
                for (var k in opt) {
                    if (opt[k].check === true) {
                        xRes += opt[k].score
                    }
                }
            }
            let end = {}
            let xEnd = {}
            for (var o in warning) {
                if (warning[o].max_score >= xRes && xRes > warning[o].min_score) {
                    end.results_assessment = warning[o]
                    end.score = xRes
                    that.setData({
                        warning: end
                    })
                }
            }
            for (var o in xWarning) {
                if (xWarning[o].max_score >= xRes && xRes > xWarning[o].min_score) {
                    xEnd.results_assessment = xWarning[o]
                    xEnd.score = xRes
                    that.setData({
                        xWarning: xEnd
                    })
                }
            }
            data.subjects = eva
            xData.subjects = xDeva
            wx.showLoading({
                title: '提交中',
            })
            // let week = parseInt(that.properties.week)
            console.log(data, warning)
            console.log(xData, xWarning)
            await wx.cloud.callFunction({
                name: 'scale_manage',
                data: {
                    action: "add_scale_return_by_user",
                    dataObj: {
                        answer_results: data,
                        test_results: end,
                        week: week,

                    }
                }
            }).then(res => {
                wx.cloud.callFunction({
                    name: 'scale_manage',
                    data: {
                        action: "add_scale_return_by_user",
                        dataObj: {
                            answer_results: xData,
                            test_results: xEnd,
                            week: week
                        }
                    }
                }).then(() => {
                    // 提交用户信息表
                    if (3 > week) {
                        wx.cloud.callFunction({
                            name: "user",
                            data: {
                                action: "edit",
                                formdata: form
                            }
                        }).then()
                    }
                })
                wx.showLoading({
                    title: '提交中',
                    success: () => {
                        let time = utils.formatTime_chinese(new Date())
                        if(3>week){
                            that.setData({
                                maxwidth: '100',
                                maxheight: '100',
                                time: time,
                                warning: end
                            })
                        }else{
                            that.setData({
                                maxwidth: '100',
                                maxheight: '0',
                                time: time,
                                warning: end
                            })
                        }
                        wx.showToast({
                            title: '提交成功',
                            icon: 'none',
                            success : () => {
                              console.log('提交成功')
                               wx.switchTab({
                                 url: '/pages/navigation/using/index',
                               })
                            }
                        })
                    }
                })
            })
        },

        xBack: function () {
            let that = this
            let turn = that.properties.turn
            if (turn === true) {
                wx.redirectTo({
                    url: '/common/pages/user/edit/index',
                })
            } else {
                wx.switchTab({
                    url: '/pages/pding/index',
                })
            }
        },

        xPickerChange: function (e) {
            let that = this
            let value = e.detail.value
            let key = e.currentTarget.dataset.key
            let arr = []
            let data = that.data
            for (var i in data) {
                if (i === key) {
                    arr = data[i]
                }
            }
            that.setData({
                [`form.${key}`]: arr[value]
            })
        },

        xPickerDate: function (e) {
            let that = this
            let value = e.detail.value
            let key = e.currentTarget.dataset.key
            that.setData({
                [`form.${key}`]: value
            })
        },

        xInput: function (e) {
            let that = this
            let value = e.detail.value
            let key = e.currentTarget.dataset.key
            that.setData({
                [`form.${key}`]: value
            })
        },

        xLocation: function () {
            let that = this
            // wx.showLoading({
            //     title: '请稍等',
            // })
            // wx.getLocation({
            //     type: 'wgs84',
            //     success(res) {
            //         const latitude = res.latitude
            //         const longitude = res.longitude
            //         const speed = res.speed
            //         const accuracy = res.accuracy
            //         wx.request({
            //             url: `https://apis.map.qq.com/ws/geocoder/v1/?key=CQ3BZ-OXQKP-7RLDJ-L4FP5-VLIIH-ENFXZ&location=` + latitude + ',' + longitude,
            //             success: res => {
            //                 let address = res.data.result.address_component
            //                 let city = address.city
            //                 let area = address.district
            //                 that.setData({
            //                     [`form.city`]: city + '-' + area
            //                 })
            //                 wx.hideLoading()
            //             }
            //         })
            //     }
            // })
        },

        xGetUser: function () {
            let that = this
            let week = that.data.week
            wx.cloud.callFunction({
                name: "user",
                data: {
                    action: "detail"
                }
            }).then(res => {
                let data = res.result
                  that.setData({
                    form : data
                  })
                if(week < 3){
                    that.xHaveEval(data.user_id)
                }
            })
        },

        xHaveEval: function (id) {
            let that = this
            wx.cloud.callFunction({
                name: 'digital_therapy',
                data: {
                    action: "get_treatment_stage_by_userid",
                    user_openid: id
                }
            }).then( res => {
                let data = res.result.test_result
                if(data.length > 0){
                    for(var i in data){
                        if(data[i].week === 0){
                            that.setData({
                                maxheight : 100
                            })
                            wx.showModal({
                                title: "提示",
                                content: "以下信息请如实填写，方便咨询师提前了解您的基本情况，提高一对一访谈时的效率。另外，我们会严格遵守保密协议。",
                                showCancel: false,
                            })
                            break;
                        }
                    }
                }else{
                    wx.showModal({
                        title: "提示",
                        content: "回忆一下最近2周的情绪状态，根据描述评估大概出现的天数作答。",
                        showCancel: false,
                    })
                    that.setData({
                        maxheight : 0
                    })
                }
            })
        }
    },

})
